package org.ezplatform.office.meeting.setting.type.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.meeting.info.web.rest.ApplyRecordWebApiController;
import org.ezplatform.office.meeting.setting.type.dao.MeetingTypeDao;
import org.ezplatform.office.meeting.setting.type.entity.MeetingType;
import org.ezplatform.util.SqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class MeetingTypeService extends BaseService<MeetingType, String>{
	private final static Logger LOGGER = LoggerFactory.getLogger(ApplyRecordWebApiController.class);
	
    @Autowired
    private MeetingTypeDao meetingTypedao;
    
    @Autowired
	private CmpPermissionService cmpPermissionService;
    
    @Override
    protected JpaBaseDao<MeetingType, String> getEntityDao() {
        return this.meetingTypedao;
    }

    /**
	 * 获取列表数据(分页)
	 * @param request
	 * @return
	 */
	public Page findByPage(Pageable pageable, String corpId, String typeName,WebUser webUser) {
		LOGGER.debug("-----findByPage----");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select t.id, t.type_name typeName, u.user_name createdBy, t.sort_no sortNo from oa_meeting_type t");
		sql.append(" left join sys_user u on t.createdBy=u.id");
		sql.append(" where t.corp_id=:corpId");
		if(StringUtils.isNotBlank(typeName)) {
			typeName=SqlUtils.escapeNormalChars(typeName);
			sql.append(" and t.type_name like :typeName "+SqlUtils.getSQLEscape(typeName));
			paramMap.put("typeName", "%"+ typeName +"%");
		}
		
		String perSql = cmpPermissionService.getBusinessScopeSql("t", webUser, "meeting:type:03");
		LOGGER.debug("---perSql:"+perSql);
		sql.append(perSql);
		sql.append(" order by t.sort_no,t.createdDate desc");
		paramMap.put("corpId", corpId);
		LOGGER.debug("---sql:"+sql);
		return super.findByPageNativeSQL(pageable, sql.toString(), paramMap);
	}
	
	/**
	 * 获取会议类型数据
	 * @return
	 */
	public List<Map> getMeetingTypes(String corpId) {
		StringBuffer sql = new StringBuffer();
		sql.append("select id, type_name as name from oa_meeting_type where corp_id = :corpId");
		sql.append(" order by sort_no,createdDate desc");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		return super.findByListNativeQuery(sql.toString(), null, paramMap);
	}
}